<?php

namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Services\RebateServices;
use App\Http\Services\SystemServices;
use App\Http\Services\UserServices;
use App\Lib\Response;
use Carbon\Carbon;
use DateInterval;
use DatePeriod;
use DateTime;
use Illuminate\Http\Request;


class RebateController extends BaseController
{
    protected $rebateService;
    protected $sys_service;
    protected $userService;

    public function __construct()
    {
        $this->sys_service = new SystemServices();
        $this->userService = new UserServices();
        $this->rebateService = new RebateServices();
    }

    /**
     * 获取返利活动配置信息
     */
    public function getConfig(){
        //获取后台配置
        $sysConfig = $this->sys_service->get_config();
        $rebateConfig = isset($sysConfig['dd_rebate_config']) ? json_decode($sysConfig['dd_rebate_config']['value'],true) : [];
        if(empty($rebateConfig)){
            Response::returnResult(Hint::ERR_NORMAL,[],'配置参数失效');
        }
        
        $ddLevel = $rebateConfig['ddLevel'];
        $ddRate = $rebateConfig['ddRate']/100;

        $rule = '1.甜枕惊喜福利，累计DD值领取钻石。'.PHP_EOL.
                '2.根据用户在平台的活跃行为，免费赠送“DD值”。'.PHP_EOL.
                '3.每周累计达到'.$ddLevel.'  DD值，次周周一领取钻石奖励（周一24点前未领取视为自愿放弃，不可补发）。'.PHP_EOL.
                '4.奖励钻石为上周DD值的'.$ddRate.'%。'.PHP_EOL.
                '5.本活动最终解释权为甜枕所有，如遇任何违规经查证，官方有权取消违规账号奖励，且对账号进行封禁处理。'
        ;
        //活动开始时间/结束时间
        $start = $rebateConfig['start_time'];
        $end = $rebateConfig['end_time'];
        $dateCount = $this->getStartAndEndTimeByDate($start, $end);
        
        //本周开始结束时间
        $todayWeekStart = Carbon::now()->startOfWeek()->toDateString();
        $todayWeekEnd = Carbon::now()->endOfWeek()->toDateString();
        if(isset($dateCount[$todayWeekStart]) && $todayWeekStart < $end){
            $nowCount = $dateCount[$todayWeekStart]['count'];
            $nowCount = numberToChinese($nowCount);
            //期数
            $nowRoundStr = '第'.$nowCount.'期:'.$todayWeekStart.'-'.$todayWeekEnd;
        }else{
            $nowRoundStr = '活动已结束';
        }
        
        $data = [
            'rule' => $rule,
            'start_time' => $start,
            'end_time' => $end,
            'now_round_str' => $nowRoundStr,
        ];
        Response::returnResult(Hint::SUCCESS,$data);
    }

    /**
     * 获取用户上周和本周的DD值
     */
    public function getUserAward(Request $request){
        //获取用户信息
        $userInfo = $this->userService->get_current_user();
        if(empty($userInfo)){
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $userId = $userInfo['user_id'];
        $res = $this->rebateService->getUserDDvalue($userId);
        Response::returnResult($res['code'],$res['data'],$res['msg']);
    }

    /**
     * 领取奖励
     */
    public function sendAward(Request $request){
        //获取用户信息
        $userInfo = $this->userService->get_current_user();
        if(empty($userInfo)){
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $userId = $userInfo['user_id'];
        //奖励id
        $awardId = $request->get('lastWeekDataId',0);
        if(empty($awardId)){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->rebateService->sendAward($userId, $awardId);
        Response::returnResult($res['code'],$res['data'],$res['msg']);
    }

    /**
     * 根据时间范围获取期数
     */
    public function getStartAndEndTimeByDate($startDate, $endDate)
    {
        $start = new DateTime($startDate);
        $end = new DateTime($endDate);
        $end->modify('next sunday'); // 确保结束日期是下一个周日
        $interval = new DateInterval('P7D'); // 每7天为一周
        $period = new DatePeriod($start, $interval, $end);
    
        $groups = [];
        foreach ($period as $k=>$week) {
            $key = $week->format('Y-m-d'); // 周的起始日期作为数组的键
            $groups[$key] = []; // 初始化该周的数组
        }
        $count = 1;
        for ($current = $start; $current <= $end; $current->modify('+1 day')) {
            $day = $current->format('Y-m-d');
            if (isset($groups[$day])) {
                // 当前日期是周的开始日期，将其加入到对应的周数组中
                $groups[$day]['date'] = $current->format('Y-m-d');
                $groups[$day]['count'] = $count;
                $count = $count+1;
            }
        }
    
        return $groups;
    }
}